#include <iostream>
#include <string>
#include <unordered_map>
#include <vector>
#include <memory>
#include <sstream>
#include <chrono>
#include <iomanip>

struct Message {
    std::string from;
    std::string to;
    std::string content;
    std::string timestamp;
    
    Message(const std::string& f, const std::string& t, const std::string& c) 
        : from(f), to(t), content(c) {
        auto now = std::chrono::system_clock::now();
        auto time = std::chrono::system_clock::to_time_t(now);
        std::stringstream ss;
        ss << std::put_time(std::localtime(&time), "%H:%M:%S");
        timestamp = ss.str();
    }
};

struct PrivateChat {
    std::string user1;
    std::string user2;
    std::vector<Message> messages;
    
    PrivateChat(const std::string& u1, const std::string& u2) : user1(u1), user2(u2) {}
    
    void addMessage(const Message& msg) {
        messages.push_back(msg);
    }
    
    void showHistory() const {
        std::cout << "\n📋 聊天记录 [" << user1 << " ↔ " << user2 << "]:" << std::endl;
        std::cout << std::string(50, '-') << std::endl;
        if (messages.empty()) {
            std::cout << "  暂无聊天记录" << std::endl;
        } else {
            for (const auto& msg : messages) {
                std::cout << "[" << msg.timestamp << "] " << msg.from << " -> " << msg.to 
                         << ": " << msg.content << std::endl;
            }
        }
        std::cout << std::string(50, '-') << std::endl;
    }
};

class SimpleChatSystem {
private:
    std::unordered_map<std::string, bool> users; // username -> isOnline
    std::unordered_map<std::string, std::shared_ptr<PrivateChat>> chats; // chatId -> chat
    
    std::string getChatId(const std::string& user1, const std::string& user2) {
        if (user1 < user2) {
            return user1 + "_" + user2;
        } else {
            return user2 + "_" + user1;
        }
    }
    
public:
    bool login(const std::string& username) {
        if (username.empty()) {
            std::cout << "❌ 用户名不能为空" << std::endl;
            return false;
        }
        
        users[username] = true;
        std::cout << "✅ " << username << " 登录成功！" << std::endl;
        return true;
    }
    
    bool sendMessage(const std::string& from, const std::string& to, const std::string& content) {
        if (users.find(from) == users.end() || !users[from]) {
            std::cout << "❌ 发送者 " << from << " 未登录" << std::endl;
            return false;
        }
        
        if (users.find(to) == users.end() || !users[to]) {
            std::cout << "❌ 接收者 " << to << " 未登录" << std::endl;
            return false;
        }
        
        std::string chatId = getChatId(from, to);
        
        // 创建聊天会话（如果不存在）
        if (chats.find(chatId) == chats.end()) {
            chats[chatId] = std::make_shared<PrivateChat>(from, to);
            std::cout << "💬 创建新的聊天会话: " << chatId << std::endl;
        }
        
        Message msg(from, to, content);
        chats[chatId]->addMessage(msg);
        
        std::cout << "📤 消息已发送: [" << msg.timestamp << "] " 
                 << from << " -> " << to << ": " << content << std::endl;
        return true;
    }
    
    void showChatHistory(const std::string& user1, const std::string& user2) {
        std::string chatId = getChatId(user1, user2);
        auto it = chats.find(chatId);
        if (it != chats.end()) {
            it->second->showHistory();
        } else {
            std::cout << "❌ 未找到 " << user1 << " 和 " << user2 << " 之间的聊天记录" << std::endl;
        }
    }
    
    void showOnlineUsers() {
        std::cout << "\n👥 在线用户列表:" << std::endl;
        for (const auto& pair : users) {
            if (pair.second) {
                std::cout << "  🟢 " << pair.first << std::endl;
            }
        }
    }
    
    void showAllChats() {
        std::cout << "\n💬 所有聊天会话:" << std::endl;
        if (chats.empty()) {
            std::cout << "  暂无聊天会话" << std::endl;
        } else {
            for (const auto& pair : chats) {
                auto chat = pair.second;
                std::cout << "  📱 " << chat->user1 << " ↔ " << chat->user2 
                         << " (消息数: " << chat->messages.size() << ")" << std::endl;
            }
        }
    }
};

void showWelcome() {
    std::cout << "\n" << std::string(60, '=') << std::endl;
    std::cout << "    🚀 单聊演示系统 - 一对一聊天体验" << std::endl;
    std::cout << std::string(60, '=') << std::endl;
    std::cout << "💡 支持多用户登录和私密聊天" << std::endl;
    std::cout << "✨ 实时消息传递和聊天记录查看" << std::endl;
}

void showCommands() {
    std::cout << "\n📋 可用命令:" << std::endl;
    std::cout << "  login <用户名>              - 用户登录" << std::endl;
    std::cout << "  send <发送者> <接收者> <消息> - 发送消息" << std::endl;
    std::cout << "  history <用户1> <用户2>     - 查看聊天记录" << std::endl;
    std::cout << "  users                       - 查看在线用户" << std::endl;
    std::cout << "  chats                       - 查看所有聊天" << std::endl;
    std::cout << "  demo                        - 运行自动演示" << std::endl;
    std::cout << "  help                        - 显示帮助" << std::endl;
    std::cout << "  quit                        - 退出程序" << std::endl;
}

void runAutoDemo(SimpleChatSystem& chatSystem) {
    std::cout << "\n🎬 自动演示开始..." << std::endl;
    
    // 1. 登录两个用户
    std::cout << "\n📱 步骤1: 用户登录" << std::endl;
    chatSystem.login("Alice");
    chatSystem.login("Bob");
    
    // 2. 发送消息
    std::cout << "\n💬 步骤2: 开始聊天" << std::endl;
    chatSystem.sendMessage("Alice", "Bob", "嗨 Bob，你好！");
    chatSystem.sendMessage("Bob", "Alice", "嗨 Alice，很高兴认识你！");
    chatSystem.sendMessage("Alice", "Bob", "今天天气真不错");
    chatSystem.sendMessage("Bob", "Alice", "是的，适合出去走走");
    
    // 3. 查看聊天记录
    std::cout << "\n📋 步骤3: 查看聊天记录" << std::endl;
    chatSystem.showChatHistory("Alice", "Bob");
    
    // 4. 显示在线用户和聊天会话
    chatSystem.showOnlineUsers();
    chatSystem.showAllChats();
    
    std::cout << "\n🎉 演示完成！" << std::endl;
}

std::vector<std::string> parseCommand(const std::string& input) {
    std::vector<std::string> tokens;
    std::istringstream iss(input);
    std::string token;
    
    while (iss >> token) {
        tokens.push_back(token);
    }
    
    return tokens;
}

int main() {
    SimpleChatSystem chatSystem;
    showWelcome();
    showCommands();
    
    std::string input;
    while (true) {
        std::cout << "\n> ";
        std::getline(std::cin, input);
        
        if (input.empty()) continue;
        
        std::vector<std::string> tokens = parseCommand(input);
        if (tokens.empty()) continue;
        
        std::string command = tokens[0];
        
        if (command == "quit" || command == "exit") {
            std::cout << "👋 再见！" << std::endl;
            break;
        } else if (command == "help") {
            showCommands();
        } else if (command == "login" && tokens.size() >= 2) {
            chatSystem.login(tokens[1]);
        } else if (command == "send" && tokens.size() >= 4) {
            std::string message;
            for (size_t i = 3; i < tokens.size(); ++i) {
                if (i > 3) message += " ";
                message += tokens[i];
            }
            chatSystem.sendMessage(tokens[1], tokens[2], message);
        } else if (command == "history" && tokens.size() >= 3) {
            chatSystem.showChatHistory(tokens[1], tokens[2]);
        } else if (command == "users") {
            chatSystem.showOnlineUsers();
        } else if (command == "chats") {
            chatSystem.showAllChats();
        } else if (command == "demo") {
            runAutoDemo(chatSystem);
        } else {
            std::cout << "❌ 未知命令或参数不足。输入 'help' 查看帮助。" << std::endl;
        }
    }
    
    return 0;
} 